import {Form, Modal, Row, Col, Input, Select, DatePicker, Divider} from 'antd';
import {useEffect, useState} from 'react';
import {connect} from 'umi';
import dayjs from 'dayjs';
import {normFile, uuid} from "@/utils/upload";
import AliyunOSSUpload from "@/components/AliyunOSSUpload/App";


const DataForm = (props) => {
  const {dispatch, submitting} = props;
  const {dataForm, setDataForm, tablePayload, setTablePayload} = props.data;
  const [form] = Form.useForm();
  const [logo, setLogo] = useState([]);
  const [cover, setCover] = useState([]);

  /* 初始化表单数据 */
  useEffect(() => {
    if (!dataForm || !dataForm.data) {
      form.setFieldsValue({status: 1});
    }
    if (dataForm && dataForm.data) {
      let logo_ = [];
      if (dataForm.data.logo) {
        logo_ = [{uuid: uuid(), name: dataForm.data.logo.split("/").pop(), status: 'done', url: dataForm.data.logo}];
      }
      setLogo(logo_)

      let cover_ = [];
      if (dataForm.data.cover) {
        cover_ = [{uuid: uuid(), name: dataForm.data.cover.split("/").pop(), status: 'done', url: dataForm.data.cover}];
      }
      setCover(cover_)

      form.setFieldsValue({
        ...dataForm.data,
        expiredDate: dataForm.data.expiredDate ? dayjs(dataForm.data.expiredDate, 'YYYY-MM-DD') : undefined,
        logo: logo_,
        cover: cover_
      });
    }
  }, [dataForm, form]);

  /* 确定操作 */
  function onOk() {
    form.validateFields().then(values => {
      if (submitting) {
        return;
      }
      let keys = Object.keys(values);
      keys.forEach(d => {
        values[d] = values[d] === null ? undefined : values[d];
      });

      if (values.logo && (values.logo.length > 0)) {
        values.logo = values.logo.filter(d => d.status === 'done').pop().url;
      } else {
        values.logo = '';
      }

      if (values.cover && (values.cover.length > 0)) {
        values.cover = values.cover.filter(d => d.status === 'done').pop().url;
      } else {
        values.cover = '';
      }

      values.expiredDate = values.expiredDate ? dayjs(values.expiredDate).format('YYYY-MM-DD') : undefined;

      dispatch({
        type: values.id ? 'PMchInfo/edit' : 'PMchInfo/add',
        payload: values,
        callback: () => {
          onCancel();
          setTablePayload({...tablePayload});
        },
      });
    });
  }

  /* 取消操作 */
  function onCancel() {
    setLogo([]);
    setCover([]);
    setDataForm(undefined);
    form.resetFields();
  }

  return (
    <Modal
      confirmLoading={submitting}
      title={dataForm ? dataForm.title : ''}
      open={dataForm ? dataForm.visible : false}
      onOk={onOk}
      onCancel={onCancel}
      forceRender={true}
      width={960}
      bodyStyle={{
        paddingTop: 24,
        maxHeight: 420,
        overflowY: 'auto',
        overflowX: 'hidden',
        paddingRight: 17
      }}
    >
      <Form layout='horizontal' labelCol={{span: 6}} form={form}>
        {dataForm && dataForm.data && (
          <Form.Item name='id' hidden={true}>
            <Input/>
          </Form.Item>
        )}
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='name' label='商家名称'
              rules={[
                {required: true, message: '商家名称不能为空'},
              ]}>
              <Input placeholder='请输入商家名称'/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='abbrevia' label='商家简称'
              rules={[
                {required: true, message: '商家简称不能为空'},
              ]}>
              <Input placeholder='请输入商家简称'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='status' label='当前状态'
              rules={[
                {required: true, message: '当前状态不能为空'},
              ]}
            >
              <Select placeholder='请选择当前状态'>
                <Select.Option value={1}>正常</Select.Option>
                <Select.Option value={0}>停用</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='expiredDate' label='到期日期'
              rules={[
                {required: false, message: '到期日期不能为空'},
              ]}>
              <DatePicker placeholder={'请选择到期日期，为空则永久不过期'} style={{width: '100%'}}/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='busiStatus' label='营业状态'
              rules={[
                {required: true, message: '营业状态不能为空'},
              ]}
            >
              <Select placeholder='请选择营业状态'>
                <Select.Option value={1}>正常</Select.Option>
                <Select.Option value={0}>休息</Select.Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='contactEmail' label='联系人邮箱'
              rules={[
                {required: false, message: '联系人邮箱不能为空'},
              ]}>
              <Input placeholder='请输入联系人邮箱'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='busiDesc' label='营业说明' tooltip="如：每天 12:00-14:00 18:00-21:00"
              rules={[
                {required: false, message: '营业说明不能为空'},
              ]}>
              <Input placeholder='请输入营业说明，如营业时间'/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='serviceTel' label='客服电话'
              rules={[
                {required: false, message: '客服电话不能为空'},
              ]}>
              <Input placeholder='请输入客服电话'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='contactName' label='联系人姓名'
              rules={[
                {required: false, message: '联系人姓名不能为空'},
              ]}>
              <Input placeholder='请输入联系人姓名'/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name='contactMobile' label='联系人手机'
              rules={[
                {required: false, message: '联系人手机不能为空'},
              ]}>
              <Input placeholder='请输入联系人手机'/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name='addr' label='商家地址'
              rules={[
                {required: false, message: '商家地址不能为空'},
              ]}>
              <Input.TextArea placeholder='请输入商家地址'/>
            </Form.Item>
          </Col>
        </Row>

        <Divider style={{marginTop: 0}}/>
        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              tooltip="宽高至少200*200px，大小5M内"
              name={'logo'}
              label="LOGO"
              rules={[
                {required: false, message: 'LOGO不能为空'},
              ]}
              valuePropName="fileList" getValueFromEvent={normFile}>
              <AliyunOSSUpload
                data={{images: logo, setImages: setLogo, size: 5, len: 1, accept: 'image/*'}}/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              tooltip="宽高至少800*800px，大小5M内"
              name={'cover'}
              label="封面图"
              rules={[
                {required: false, message: '封面图不能为空'},
              ]}
              valuePropName="fileList" getValueFromEvent={normFile}>
              <AliyunOSSUpload
                data={{images: cover, setImages: setCover, size: 5, len: 1, accept: 'image/*'}}/>
            </Form.Item>
          </Col>
        </Row>

      </Form>
    </Modal>
  );
};


export default connect(({loading}) => {
  return {
    submitting: loading.effects['PMchInfo/add'] || loading.effects['PMchInfo/edit'],
  };
})(DataForm);

